<script setup lang="ts">
// 引入必要的模块和工具函数
import { computed, ref, watch } from 'vue';
import {  useForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales'; // 国际化翻译函数
import type { ApiUserInput, ApiUserOut } from '@/api-services'; // 用户相关的API输入输出类型定义
import { UserApi } from '@/api-services/apis/user-api'; // 用户操作的API服务
import { feature, getAPI } from '@/axios-utils'; // 用于调用API的工具函数
import { queryDone } from '@/utils/api'; // 处理API响应的工具函数
import { REG_PWD, REG_USER_NAME } from '@/constants/reg'; // 正则表达式常量
import { ApiroleserviceApi } from '@/api-services/apis/apiroleservice-api'; // 角色管理的API服务
import { NetoKit } from '@/typings/neto';

// 定义组件名称
defineOptions({
  name: 'UserOperateModal'
});

// 定义组件的props
interface Props {
  /** the type of operation */
  operateType: UI.TableOperateType;
  /** the edit row data */
  rowData?: ApiUserOut | null;
}

const props = defineProps<Props>();

// 定义组件的emits
interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

// 定义visible模型，用于控制抽屉的显示与隐藏
const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useForm();
const { defaultRequiredRule } = useFormRules();

// 计算属性：根据操作类型返回标题
const title = computed(() => {
  const titles: Record<UI.TableOperateType, string> = {
    add: $t('page.manage.user.addUser'),
    edit: $t('page.manage.user.editUser')
  };
  return titles[props.operateType];
});

// 定义表单模型类型
type Model = {
  [K in keyof Pick<ApiUserInput, 'id' | 'account' | 'nick' | 'phone' | 'email'
    | 'province' | 'city' | 'town' | 'address' | 'tel' | 'isEnable' | 'remark'>]: NonNullable<
      ApiUserInput[K]
    >;
} & {
  addPwd: string; // 新增用户时的密码字段
  pwd: string | undefined; // 编辑用户时的密码字段
};

// 初始化表单模型
const model = ref(createDefaultModel());

// 创建默认的表单模型对象
function createDefaultModel(): Model {
  return {
    id: undefined,
    account: '',
    nick: '',
    addPwd: '',
    pwd: undefined,
    phone: '',
    email: '',
    isEnable: true,
    remark: ''
  };
}

// 表单验证规则
const formRules = {
  account: [
    {
      pattern: REG_USER_NAME,
      message: $t('form.userName.invalid'),
      trigger: 'change'
    },
    defaultRequiredRule
  ],
  nick: [defaultRequiredRule],
  addPwd: [
    {
      required: true,
      pattern: REG_PWD,
      message: $t('form.pwd.invalid'),
      trigger: 'change'
    }
  ]
} satisfies Record<string, App.Global.FormRule[]>;

// 存储角色选项
const roleOptions = ref<CommonType.Option<string>[]>([]);

// 获取角色选项数据
async function getRoleOptions() {
  const [err, res] = await feature(getAPI(ApiroleserviceApi).getAll());

  let roleData: { label: string; value: string }[] = [];
  queryDone(err, async () => {
    if (res?.data.data) {
      roleData = res.data.data.map(it => ({
        label: it.name!,
        value: it.id!.toString()
      }));
    }
  });
  roleOptions.value = [...roleData];
}

// 调用获取角色选项的方法
getRoleOptions();

// 初始化表单模型
function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, props.rowData);
  }
}

// 关闭抽屉的方法
function closeModal() {
  visible.value = false;
}

// 提交表单的方法
async function handleSubmit() {
  await validate(); // 验证表单

  // 提交请求
  const [err, res] = await feature(getAPI(UserApi).insertOrUpdate(model.value));

  queryDone(err, async () => {
    if (res?.data.data) {
      window.$message?.success($t('common.updateSuccess'));
      closeModal();
      emit('submitted');
    }
  });
}

// 监听visible的变化，初始化表单
watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <ElDialog v-model="visible" :title="title"  width="800">
    <ElForm ref="formRef" :model="model" :rules="formRules"  label-width="auto">
      <ElRow :gutter="16" wrap>
        <ElCol :lg="12" :xs="24">
          <!-- 用户名输入框 -->
          <ElFormItem :label="$t('page.manage.user.userName')" prop="account">
            <ElInput v-model="model.account" :placeholder="$t('page.manage.user.form.userName')" />
          </ElFormItem>
        </ElCol>
        <ElCol :lg="12" :xs="24">
          <!-- 昵称输入框 -->
          <ElFormItem :label="$t('page.manage.user.nickName')" prop="nick">
            <ElInput v-model="model.nick" :placeholder="$t('page.manage.user.form.nickName')" />
          </ElFormItem>
        </ElCol>
        <ElCol :lg="12" :xs="24">
          <!-- 添加用户时的密码输入框 -->
          <ElFormItem v-if="props.operateType === 'add'" :label="$t('page.manage.user.userPwd')" prop="addPwd">
            <ElInput v-model="model.addPwd" type="password"
              :placeholder="$t('page.login.common.passwordPlaceholder')" />
          </ElFormItem>
          <!-- 编辑用户时的密码输入框 -->
          <ElFormItem v-else :label="$t('page.manage.user.userPwd')" prop="pwd">
            <!-- 如果不修改密码，无需填写 -->
            <ElInput v-model="model.pwd" type="password" :placeholder="$t('page.manage.user.form.userPwd')" />
          </ElFormItem>
        </ElCol>
        <ElCol :lg="12" :xs="24"> <!-- 手机号输入框 -->
          <ElFormItem :label="$t('page.manage.user.userPhone')" prop="phone">
            <ElInput v-model="model.phone" :placeholder="$t('page.manage.user.form.userPhone')" />
          </ElFormItem>
        </ElCol>
        <ElCol :lg="12" :xs="24">
          <!-- 邮箱输入框 -->
          <ElFormItem :label="$t('page.manage.user.userEmail')" prop="email">
            <ElInput v-model="model.email" :placeholder="$t('page.manage.user.form.userEmail')" />
          </ElFormItem>
        </ElCol>
        <ElCol :lg="12" :xs="24">
          <!-- 用户状态开关 -->
          <ElFormItem :label="$t('page.manage.common.isEnable')" prop="isEnable">
            <ElSwitch v-model="model.isEnable" />
          </ElFormItem>
        </ElCol>

        <ElCol :lg="12" :xs="24">
          <!-- 省份 -->
          <ElFormItem :label="$t('page.manage.user.province')" prop="province">
            <ElInput v-model="model.province" :placeholder="$t('page.manage.user.form.province')" />
          </ElFormItem>
        </ElCol>

        <ElCol :lg="12" :xs="24">
          <!-- 城市 -->
          <ElFormItem :label="$t('page.manage.user.city')" prop="city">
            <ElInput v-model="model.city" :placeholder="$t('page.manage.user.form.city')" />
          </ElFormItem>
        </ElCol>


        <ElCol :lg="12" :xs="24">
          <!-- 镇 -->
          <ElFormItem :label="$t('page.manage.user.town')" prop="town">
            <ElInput v-model="model.town" :placeholder="$t('page.manage.user.form.town')" />
          </ElFormItem>
        </ElCol>


        <ElCol :lg="12" :xs="24">
          <!-- 详细地址 -->
          <ElFormItem :label="$t('page.manage.user.address')" prop="address">
            <ElInput v-model="model.address" :placeholder="$t('page.manage.user.form.address')" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem  :label="$t('page.manage.user.remark')" prop="remark">

            <ElInput type="textarea" v-model="model.remark" :auto-size="{ minRows: 2, maxRows: 5 }" />
          </ElFormItem>
        </ElCol>
      </ElRow>







    </ElForm>
    <template #footer>
      <ElSpace :size="16">
        <!-- 取消按钮 -->
        <ElButton @click="closeModal">{{ $t('common.cancel') }}</ElButton>
        <!-- 确认按钮 -->
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </ElDialog>
</template>

<style scoped></style>
